package xyz.labmem.base.sys.module.user.controller

import cn.dev33.satoken.annotation.SaCheckPermission
import cn.dev33.satoken.stp.StpUtil
import cn.hutool.core.bean.BeanUtil
import com.baomidou.mybatisplus.extension.kotlin.KtQueryWrapper
import io.swagger.annotations.Api
import io.swagger.annotations.ApiOperation
import io.swagger.annotations.ApiParam
import org.springframework.security.crypto.password.PasswordEncoder
import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.*
import xyz.labmem.base.core.annotion.BusinessLog
import xyz.labmem.base.core.base.BaseVerify
import xyz.labmem.base.core.enums.LogAnnotationOpTypeEnum
import xyz.labmem.base.core.result.RP
import xyz.labmem.base.core.result.RV
import xyz.labmem.base.core.tool.isNotBlank
import xyz.labmem.base.sys.base.BaseController
import xyz.labmem.base.sys.consts.PathPrefixConst
import xyz.labmem.base.sys.context.AuthRedisService
import xyz.labmem.base.sys.module.auth.controller.request.AuthResetPwd
import xyz.labmem.base.sys.module.menu.mapper.SysUserMenusMapper
import xyz.labmem.base.sys.module.user.controller.request.SysUserCURDReq
import xyz.labmem.base.sys.module.user.controller.request.SysUserPageReq
import xyz.labmem.base.sys.module.user.entity.SysUser
import xyz.labmem.base.sys.module.user.entity.SysUserRepeal
import xyz.labmem.base.sys.module.user.mapper.SysUserMapper
import xyz.labmem.base.sys.util.LogManager

/**
 * @Author lty
 * @Date 2021/12/17 13:59
 */
@Api(tags = ["用户管理"])
@RestController
@RequestMapping("${PathPrefixConst.SYS_PATH_PREFIX}user")
class SysUserController(
    private var sysUserMapper: SysUserMapper,
    private var passwordEncoder: PasswordEncoder,
    private var authRedisService: AuthRedisService,
    private var sysUserMenusMapper: SysUserMenusMapper
) : BaseController() {

    @PostMapping("page")
    @ApiOperation(value = "用户分页列表")
    fun userPage(@RequestBody @Validated(BaseVerify.page::class) req: SysUserPageReq): RP<List<SysUser>> {
        return page(
            sysUserMapper.selectPage(
                req.IPage(),
                KtQueryWrapper(SysUser::class.java)
                    .like(req.account.isNotBlank(), SysUser::account, req.account)
                    .like(req.username.isNotBlank(), SysUser::username, req.username)
                    .ne(SysUser::superr, 1)
                    .orderByDesc(SysUser::createTime)
            )
        )
    }

    @SaCheckPermission("super")
    @PutMapping("add")
    @ApiOperation(value = "添加用户")
    @BusinessLog(title = "添加用户", opType = LogAnnotationOpTypeEnum.ADD)
    fun addUser(@RequestBody @Validated(BaseVerify.add::class) req: SysUserCURDReq): RV<*> {
        //检查账号是否存在
        val count = sysUserMapper.selectCount(
            KtQueryWrapper(SysUser::class.java)
                .eq(SysUser::account, req.account)
        )
        return if (count == 0L) {
            val user = SysUser()
            BeanUtil.copyProperties(req, user)
            user.apply {
                password = passwordEncoder.encode(req.password)
            }
            resultJudgment(user.insert(), "注册成功", "注册失败")
        } else
            failedMsg("账号已存在")
    }

    /**
     * 修改用户
     */
    @ApiOperation(value = "修改用户")
    @SaCheckPermission("super")
    @BusinessLog(title = "修改用户", opType = LogAnnotationOpTypeEnum.UPDATE)
    @PutMapping
    fun edit(@Validated @RequestBody user: SysUser): RV<*> {
        val count = sysUserMapper.selectCount(
            KtQueryWrapper(SysUser::class.java)
                .ne(SysUser::id, user.id)
                .eq(SysUser::account, user.account)
        )
        return if (count == 0L) {
            resultJudgment(user.updateById(), "修改成功", "修改失败")
        } else
            failedMsg("账号登录名已存在")
    }
    @SaCheckPermission("super")
    @DeleteMapping("del/{userId}")
    @ApiOperation(value = "删除用户")
    @BusinessLog(title = "删除用户", opType = LogAnnotationOpTypeEnum.DELETE)
    fun delUser(@ApiParam(value = "用户id", required = true) @PathVariable userId: String): RV<*> {
        //获取账号信息
        val user = sysUserMapper.selectById(userId)
        return if (user != null) {
            val repeal = SysUserRepeal()
            BeanUtil.copyProperties(user, repeal)

            //删除菜单
            sysUserMenusMapper.deleteUserRole(user.id!!)
            if (user.deleteById()) {
                //退出日志
                LogManager.me().executeExitLog(user.account)
                //清朝session
                authRedisService.removeUserEntity(user.id!!,"")
                //退出
                StpUtil.logout(user.id)
                return successMsg("删除用户成功")
            }
            return failedMsg("删除用户失败")
        } else
            failedMsg("账号不存在")
    }


    @SaCheckPermission("super")
    @PostMapping("updatePwdById")
    @ApiOperation(value = "管理员修改他人密码")
    fun updatePwdById(@RequestBody @Validated(BaseVerify.update::class) req: AuthResetPwd): RV<Any> {
        val user = SysUser().selectById(req.id)
        if(user!=null){
            user.password = passwordEncoder.encode(req.password)
            return resultJudgment(user.updateById())
        }
        return failedMsg("密码错误！")
    }
}